package com.qyp.content.filter;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qyp.content.domain.entity.messaging.ResponseVO;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 普通的springMVC异常
 */
@Component
class MyUrlBlockHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        ResponseVO sentinelErrorMsg = null;
        // 根据异常类型区分违反哪种规则
        if(e instanceof FlowException){// 限流异常
            sentinelErrorMsg = ResponseVO.builder()
                    .code(100)
                    .msg("被限流规则阻挡")
                    .build();
        }else if(e instanceof DegradeException){ // 降级异常
            sentinelErrorMsg = ResponseVO.builder()
                    .code(101)
                    .msg("被降级规则阻挡")
                    .build();
        }else if(e instanceof ParamFlowException){ // 热点参数异常
            sentinelErrorMsg = ResponseVO.builder()
                    .code(102)
                    .msg("被热点参数规则阻挡")
                    .build();
        }else if(e instanceof SystemBlockException){ // 系统规则异常
            sentinelErrorMsg = ResponseVO.builder()
                    .code(103)
                    .msg("被系统规则阻挡")
                    .build();
        }else if(e instanceof AuthorityException){ // 认证异常
            sentinelErrorMsg = ResponseVO.builder()
                    .code(104)
                    .msg("被授权规则阻挡")
                    .build();
        }else{
            sentinelErrorMsg = ResponseVO.builder()
                    .code(999)
                    .msg("Unknown")
                    .build();
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        new ObjectMapper().writeValue(httpServletResponse.getWriter(),sentinelErrorMsg);
    }
}

